#!/usr/bin/env python3
"""
高德地图API工具集
"""

import requests
import json
from typing import Dict, Any, Optional
from ..core.tool import Tool, ToolResult

class AmapGeocodingTool(Tool):
    """高德地理编码工具"""
    
    def __init__(self, api_key: str):
        super().__init__(
            name="amap_geocoding",
            description="高德地理编码服务：地址转坐标"
        )
        self.api_key = api_key
        self.base_url = "https://restapi.amap.com/v3/geocode/geo"
    
    def execute(self, address: str, city: str = None, **kwargs) -> ToolResult:
        """执行地理编码"""
        try:
            if not self.api_key:
                return ToolResult(
                    success=False,
                    error="高德地图API密钥未配置。请设置环境变量 AMAP_API_KEY 来使用地理编码功能。"
                )
            
            params = {
                "key": self.api_key,
                "address": address,
                "city": city or ""
            }
            
            response = requests.get(self.base_url, params=params, timeout=10)
            response.raise_for_status()
            
            data = response.json()
            
            if data.get("status") == "1" and data.get("geocodes"):
                geocode = data["geocodes"][0]
                result_data = {
                    "location": geocode.get("location", ""),
                    "formatted_address": geocode.get("formatted_address", ""),
                    "province": geocode.get("province", ""),
                    "city": geocode.get("city", ""),
                    "district": geocode.get("district", ""),
                    "level": geocode.get("level", "")
                }
                
                return ToolResult(
                    success=True,
                    data=result_data,
                    metadata={
                        "api_status": data.get("status"),
                        "count": data.get("count", 0)
                    }
                )
            else:
                return ToolResult(
                    success=False,
                    error=f"地理编码失败: {data.get('info', '未知错误')}"
                )
                
        except requests.exceptions.RequestException as e:
            return ToolResult(
                success=False,
                error=f"API请求失败: {str(e)}"
            )
        except Exception as e:
            return ToolResult(
                success=False,
                error=str(e)
            )
    
    def get_schema(self) -> Dict[str, Any]:
        """获取工具调用模式"""
        return {
            "type": "function",
            "function": {
                "name": self.name,
                "description": self.description,
                "parameters": {
                    "type": "object",
                    "properties": {
                        "address": {
                            "type": "string",
                            "description": "要编码的地址"
                        },
                        "city": {
                            "type": "string",
                            "description": "城市名称（可选）"
                        }
                    },
                    "required": ["address"]
                }
            }
        }

class AmapWeatherTool(Tool):
    """高德天气工具"""
    
    def __init__(self, api_key: str):
        super().__init__(
            name="amap_weather",
            description="高德天气服务：获取天气信息"
        )
        self.api_key = api_key
        self.base_url = "https://restapi.amap.com/v3/weather/weatherInfo"
    
    def execute(self, city: str, extensions: str = "base", **kwargs) -> ToolResult:
        """执行天气查询"""
        try:
            if not self.api_key:
                return ToolResult(
                    success=False,
                    error="高德地图API密钥未配置。请设置环境变量 AMAP_API_KEY 来使用天气查询功能。"
                )
            
            params = {
                "key": self.api_key,
                "city": city,
                "extensions": extensions
            }
            
            response = requests.get(self.base_url, params=params, timeout=10)
            response.raise_for_status()
            
            data = response.json()
            
            if data.get("status") == "1" and data.get("lives"):
                weather = data["lives"][0]
                result_data = {
                    "city": weather.get("city", ""),
                    "weather": weather.get("weather", ""),
                    "temperature": weather.get("temperature", ""),
                    "wind_direction": weather.get("wind_direction", ""),
                    "wind_power": weather.get("wind_power", ""),
                    "humidity": weather.get("humidity", ""),
                    "report_time": weather.get("report_time", "")
                }
                
                return ToolResult(
                    success=True,
                    data=result_data,
                    metadata={
                        "api_status": data.get("status"),
                        "extensions": extensions
                    }
                )
            else:
                return ToolResult(
                    success=False,
                    error=f"天气查询失败: {data.get('info', '未知错误')}"
                )
                
        except requests.exceptions.RequestException as e:
            return ToolResult(
                success=False,
                error=f"API请求失败: {str(e)}"
            )
        except Exception as e:
            return ToolResult(
                success=False,
                error=str(e)
            )
    
    def get_schema(self) -> Dict[str, Any]:
        """获取工具调用模式"""
        return {
            "type": "function",
            "function": {
                "name": self.name,
                "description": self.description,
                "parameters": {
                    "type": "object",
                    "properties": {
                        "city": {
                            "type": "string",
                            "description": "城市名称"
                        },
                        "extensions": {
                            "type": "string",
                            "enum": ["base", "all"],
                            "description": "返回信息类型：base基础信息，all详细信息"
                        }
                    },
                    "required": ["city"]
                }
            }
        }

class AmapPOITool(Tool):
    """高德POI搜索工具"""
    
    def __init__(self, api_key: str):
        super().__init__(
            name="amap_poi",
            description="高德POI搜索服务：搜索兴趣点"
        )
        self.api_key = api_key
        self.base_url = "https://restapi.amap.com/v3/place/text"
    
    def execute(self, keywords: str, city: str = None, location: str = None, 
                types: str = None, **kwargs) -> ToolResult:
        """执行POI搜索"""
        try:
            if not self.api_key:
                return ToolResult(
                    success=False,
                    error="高德地图API密钥未配置。请设置环境变量 AMAP_API_KEY 来使用POI搜索功能。"
                )
            
            params = {
                "key": self.api_key,
                "keywords": keywords,
                "city": city or "",
                "location": location or "",
                "types": types or "",
                "page": 1,
                "offset": 10
            }
            
            response = requests.get(self.base_url, params=params, timeout=10)
            response.raise_for_status()
            
            data = response.json()
            
            if data.get("status") == "1" and data.get("pois"):
                pois = data["pois"]
                result_data = {
                    "total": data.get("count", 0),
                    "pois": []
                }
                
                for poi in pois[:5]:  # 只返回前5个结果
                    poi_info = {
                        "name": poi.get("name", ""),
                        "address": poi.get("address", ""),
                        "location": poi.get("location", ""),
                        "tel": poi.get("tel", ""),
                        "type": poi.get("type", ""),
                        "distance": poi.get("distance", "")
                    }
                    result_data["pois"].append(poi_info)
                
                return ToolResult(
                    success=True,
                    data=result_data,
                    metadata={
                        "api_status": data.get("status"),
                        "search_keywords": keywords
                    }
                )
            else:
                return ToolResult(
                    success=False,
                    error=f"POI搜索失败: {data.get('info', '未知错误')}"
                )
                
        except requests.exceptions.RequestException as e:
            return ToolResult(
                success=False,
                error=f"API请求失败: {str(e)}"
            )
        except Exception as e:
            return ToolResult(
                success=False,
                error=str(e)
            )
    
    def get_schema(self) -> Dict[str, Any]:
        """获取工具调用模式"""
        return {
            "type": "function",
            "function": {
                "name": self.name,
                "description": self.description,
                "parameters": {
                    "type": "object",
                    "properties": {
                        "keywords": {
                            "type": "string",
                            "description": "搜索关键词"
                        },
                        "city": {
                            "type": "string",
                            "description": "城市名称（可选）"
                        },
                        "location": {
                            "type": "string",
                            "description": "中心点坐标（可选）"
                        },
                        "types": {
                            "type": "string",
                            "description": "POI类型（可选）"
                        }
                    },
                    "required": ["keywords"]
                }
            }
        }
